package com.project.slsx.activity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.project.slsx.Constant.Constans;
import com.project.slsx.R;
import com.project.slsx.adapter.PurchaseResultAdapter;
import com.project.slsx.adapter.PurchCategoryAdapter;
import com.project.slsx.bean.CategoryBean;
import com.project.slsx.bean.PurchaseResultBean;
import com.project.slsx.utils.DialogUtils;
import com.project.slsx.utils.ParamsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 采购
 */

public class PurchaseActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = PurchaseActivity.class.getSimpleName();
    private PurchaseResultAdapter purchaseResultAdapter;
    private PurchCategoryAdapter purchCategoryAdapter;
    private RecyclerView rv;
    private ArrayList<Boolean> categorySelected;
    private String searchStr = "";
    private SmartRefreshLayout sfl;
    private int page = 1;
    private CategoryBean categoryBean;
    private String cid = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_purchase;
    }

    @Override
    public void initView() {
        TextView title = findViewById(R.id.tv_title);
        title.setText("采购");
        findViewById(R.id.rl_back).setOnClickListener(v -> finish());
        TextView tvRight = findViewById(R.id.tv_right);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("清空");

        EditText edSearch = findViewById(R.id.ed_storage_search);
        edSearch.addTextChangedListener(new MyWatcher());
        findViewById(R.id.btn_purchase_search).setOnClickListener(this);

        sfl = findViewById(R.id.smartrefreshlayout);
        RecyclerView rvCategory = findViewById(R.id.recyclerview_purchase_category);
        rvCategory.setLayoutManager(new LinearLayoutManager(this));
        purchCategoryAdapter = new PurchCategoryAdapter(R.layout.layout_item_cash_right);
        rvCategory.setAdapter(purchCategoryAdapter);

        rv = findViewById(R.id.recyclerview_purchase);
        rv.setLayoutManager(new LinearLayoutManager(this));
        purchaseResultAdapter = new PurchaseResultAdapter(R.layout.layout_item_purchase);
        rv.setAdapter(purchaseResultAdapter);
    }

    @Override
    public void initData() {
        categorySelected = new ArrayList<>();
        purchCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            ArrayList<Boolean> selectedIndex = purchCategoryAdapter.getSelectedIndex();
            for (int i = 0; i < selectedIndex.size(); i++) {
                if (i == position) {
                    purchCategoryAdapter.getSelectedIndex().set(i, true);
                } else {
                    purchCategoryAdapter.getSelectedIndex().set(i, false);
                }
                purchCategoryAdapter.notifyDataSetChanged();
            }
            List data = adapter.getData();
            CategoryBean.ResultBean resultBean = (CategoryBean.ResultBean) data.get(position);
            cid = resultBean.getId();
            getPurchaseDataList(cid, true);
        });

        sfl.autoRefresh();
        sfl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refreshlayout(refreshLayout, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                refreshlayout(refreshLayout, true);
            }
        });

        //获取
        HttpParams categorylistParams = ParamsUtils.getCategorylistParams();
        getCid(categorylistParams);

        purchaseResultAdapter.setOnItemEditListener((item, position, b) -> {
            doPurchaseedit(item, b);
        });

    }

    //采购编辑接口
    private void doPurchaseedit(PurchaseResultBean.ResultBean item, boolean b) {
        HttpParams purchaseeditParams = ParamsUtils.getPurchaseeditParams();
        purchaseeditParams.put("cid", cid);
        purchaseeditParams.put("goods_id", item.getGoods_id());
        purchaseeditParams.put("option_id", item.getOption_id());
        purchaseeditParams.put("title", item.getTitle());
        purchaseeditParams.put("number", item.getTotal());
        purchaseeditParams.put("supplier_id", item.getSupplier().get(0).getId());
        purchaseeditParams.put("price", 100);
        OkGo.<String>post(Constans.BASEURL).tag("purchaseedit").params(purchaseeditParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);

            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        });
    }

    private void refreshlayout(RefreshLayout refreshLayout, boolean b) {
        refreshLayout.getLayout().postDelayed(() -> {
            if (b) {
                //下拉
                page = 1;
            } else {
                //上拉加载更多
                ++page;
            }
            getPurchaseDataList(cid, b);
        }, 50);
    }

    /**
     * 获取店铺列表
     *
     * @param categorylistParams
     */
    private void getCid(HttpParams categorylistParams) {
        OkGo.<String>post(Constans.BASEURL).tag("categorylist").params(categorylistParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                categoryBean = JSONObject.parseObject(response.body(), CategoryBean.class);
                if (categoryBean.getErrno() == Constans.SUCCESS) {
                    for (int i = 0; i < categoryBean.getResult().size(); i++) {
                        if (i == 0) {
                            categorySelected.add(true);
                        } else {
                            categorySelected.add(false);
                        }
                    }
                    purchCategoryAdapter.setNewData(categoryBean.getResult());
                    purchCategoryAdapter.setItemSelected(categorySelected);
                    cid = categoryBean.getResult().get(0).getId();
                } else {
                    showToast(mContext, categoryBean.getErrmsg());
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                showToast(mContext, "网络错误");
            }
        });
    }

    /**
     * 采购列表
     *
     * @param
     */
    private void getPurchaseDataList(String id, boolean b) {
        HttpParams purchasesearchParams = ParamsUtils.getPurchasesearchParams();
        purchasesearchParams.put("cid", id);
        purchasesearchParams.put("page", page);
        purchasesearchParams.put("keyword", searchStr);
        OkGo.<String>post(Constans.BASEURL).tag("purchasesearch").params(purchasesearchParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                PurchaseResultBean purchaseResultBean = JSONObject.parseObject(response.body(), PurchaseResultBean.class);
                if (b) {
                    if (purchaseResultBean.getErrno() == Constans.SUCCESS) {
                        if (purchaseResultBean.getResult() != null && purchaseResultBean.getResult().size() > 0) {
                            purchaseResultAdapter.setNewData(purchaseResultBean.getResult());
                        } else {
                            showToast(mContext, "无数据");
                        }
                    } else {
                        showToast(mContext, "无数据");
                    }
                } else {
                    if (purchaseResultBean.getErrno() == Constans.SUCCESS) {
                        if (purchaseResultBean.getResult() != null && purchaseResultBean.getResult().size() > 0) {
                            purchaseResultAdapter.addData(purchaseResultBean.getResult());
                        } else {
                            showToast(mContext, "没有更多数据");
                        }
                    }
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                showToast(mContext, "网络错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (b) {
                    sfl.finishRefresh();
                } else {
                    sfl.finishLoadMore();
                }
            }
        });
    }

    private List<String> getList() {
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            strings.add("item:" + i);
        }

        return strings;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btn_purchase_search:
                doSearch();
                break;
        }
    }

    /**
     * 采购搜索
     */
    private void doSearch() {
        page = 1;
        HttpParams purchasesearchParams = ParamsUtils.getPurchasesearchParams();
        purchasesearchParams.put("cid", cid);
        purchasesearchParams.put("page", page);
        purchasesearchParams.put("keyword", searchStr);
        OkGo.<String>post(Constans.BASEURL).tag("list").params(purchasesearchParams).execute(new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                DialogUtils.showLoading(null, getSupportFragmentManager());
            }

            @Override
            public void onSuccess(Response<String> response) {
                PurchaseResultBean purchaseResultBean = JSONObject.parseObject(response.body(), PurchaseResultBean.class);
                if (purchaseResultBean.getErrno() == Constans.SUCCESS) {
                    if (purchaseResultBean.getResult() != null && purchaseResultBean.getResult().size() > 0) {
                        purchaseResultAdapter.setNewData(purchaseResultBean.getResult());
                    } else {
                        showToast(mContext, "无数据");
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                showToast(mContext, "网络问题");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtils.dissmissDialog();
            }
        });

    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            searchStr = s.toString().trim();
        }
    }
}
